export function isObject(data) {
  return typeof data === 'object' && data!==null
}

export function isReservedTag(tagName) {
  let str = 'p,div,span,li,input,button'
  let obj = {}
  str.split(',').forEach(tag => {
    obj[tag] = true
  })
  return obj[tagName]
}

export function def(data, key, value){
  Object.defineProperty(data, key, {
    enumerable: false,
    configurable: false,
    value
  })
}

export function proxy(vm, source, key) {
  Object.defineProperty(vm, key, {
    get() {
      return vm[source][key]
    },
    set(newVal) {
      vm[source][key] = newVal
    }
  })
}

const LIFECYCLE_HOOKS = [
  'beforeCreate',
  'created',
  'beforeMount',
  'mounted',
  'beforeUpdate',
  'updated',
  'beforeDestroy',
  'destroyed'
]

let strats = {}
function mergeHook(parentVal, childVal) {
  if(childVal) {
    if(parentVal) {
      return parentVal.concat(childVal)
    }else{
      return [childVal]
    }
  }else{
    return parentVal
  }
}

LIFECYCLE_HOOKS.forEach(hook => {
  strats[hook] = mergeHook
})

function mergeAssets(parentVal, childVal) {
  const res = Object.create(parentVal)
  for(let key in childVal) {
    res[key] = childVal[key]
  }
  return res
}

strats.components = mergeAssets

export function mergeOptions(parent, child) {

  const options = {}
  for(let key in parent) {
    mergeField(key)
  }
  for(let key in child) {
    if(!parent.hasOwnProperty(key)){
      mergeField(key)
    }
  }
  // 有些属性 要有特殊的处理
  function mergeField(key) {
    if(strats[key]) {
      return options[key] = strats[key](parent[key], child[key])
    }
    if(typeof parent[key] === 'object' && typeof child[key]==='object'){
      options[key] = {
        ...parent[key],
        ...child[key]
      }
    }else if(child[key] == null) {
      options[key] = parent[key]
    }else{
      options[key] = child[key]
    }
  }
  return options
}